﻿using System;
using PhiStore.Threading;
using System.Text;

namespace PhiStore.ExampleCodes.PhiLog
{
    class PhiLogSpammer : Boostable
    {
        private object mutex = new object();

        private DateTime start;
        private decimal throughput = 0;
        private PhiLog log;

        private bool stop = false;
        private string sizeSeed = "";

        private string newSizeSeed(int size)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < size; i++)
            {
                sb.Append((char)i);
            }
            return sb.ToString();
        }

        public PhiLogSpammer(uint replications, bool encryptConnection, bool compressObjects, bool encryptObjects, bool use2PC)
        {
            log = new PhiLog(replications, encryptConnection, compressObjects, encryptObjects, use2PC);
            //sizeSeed = newSizeSeed(1);
            Booster.Boost(this);
        }


        /// <summary>
        /// number of logentries pr. second
        /// </summary>
        public decimal ThroughPut
        {
            get
            {
                decimal result = 0;
                lock (mutex)
                {
                    result = throughput;
                }
                return result;
            }
        }

        public void STOP()
        {
            lock (mutex)
            {
                stop = true;
            }
        }


        public void Run()
        {
            ulong LogId = 0L;
            double SecondsUsed = 0;
            try
            {
                while (true)
                {

                    lock (mutex)
                    {
                        if (stop)
                        {
                            log.Stop();
                            break;
                        }
                    }
                    start = DateTime.Now;

                    for (int i = 0; i < 100; i++)
                    {
                        log.addLogEntry("Spammer", "Message" + LogId++.ToString() + " " + sizeSeed);
                    }
                    lock (mutex)
                    {
                        TimeSpan ts = DateTime.Now.Subtract(start);
                        throughput = Convert.ToDecimal(100) / Convert.ToDecimal(ts.TotalSeconds);

                        SecondsUsed += ts.TotalSeconds;

                        Console.WriteLine(LogId + " " + throughput.ToString("N2") + " " + sizeSeed.Length);
                        //sizeSeed = newSizeSeed(sizeSeed.Length * 2);

                    }
                }
            }
            catch (Exception)
            {
                //byebye
            }
            Console.WriteLine("Average throughput: " + (Convert.ToDouble(LogId) / SecondsUsed).ToString("N2"));
        }
    }
}
